package it.evento.controllers;

/*
 * Spike Google Calendar, tramite OAuth 2.0 otteniamo authentication token per accedere ai servizi
 */
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient.AccessToken;
import com.restfb.json.JsonObject;
import com.restfb.types.User;
import it.evento.BusinessLogic;
import it.evento.Users;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import it.evento.manager.FacebookManager;
import it.evento.utils.genpage.ContentGenerator;

import java.io.IOException;
import javax.ejb.EJB;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonBuilderFactory;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Mark
 */
@WebServlet(urlPatterns = {"/FacebookController"})
public class FacebookController extends HttpServlet {
    
    @EJB
    private BusinessLogic businessLogic;
    
    private final JsonBuilderFactory factory = Json.createBuilderFactory(null);
    private JsonArray jsonArray = null;
    private HttpSession session;

    FacebookManager fm = new FacebookManager();
    
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        session = request.getSession();
        
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            if(request.getParameter("userauth") != null) {
                String access_token = request.getParameter("accesstoken");
                String fbuid = request.getParameter("fbuid");
                Users loggedUser = (Users)session.getAttribute("loggedUser");
                
                if(loggedUser==null)
                    return;
                
                if(loggedUser.getFacebook()==null) {
                    loggedUser.setFacebook(fbuid);
                    businessLogic.updateUser(loggedUser.getId(), loggedUser);
                }
                
                if(!loggedUser.getFacebook().equals(fbuid)) {
                    jsonArray = factory.createArrayBuilder()
                                        .add(factory.createObjectBuilder()
                                            .add("status", 1)
                                            .add("message", ContentGenerator.printError("L'account con cui hai effettuato il login su Facebook non conicide con quello di EvenTo."
                                                                                      + "<br>Per favore accedi alla pagina del Profilo ed effettua il login con l'utente corretto.")))
                                        .build();
                }
                else {
                    DefaultFacebookClient dfcu = new DefaultFacebookClient(access_token, FacebookManager.FB_SECRET);
                    JsonObject me = dfcu.fetchObject("me", JsonObject.class);
                    
                    if(me != null) {
                        session.setAttribute("facebook", dfcu);
                        
                        jsonArray = factory.createArrayBuilder()
                                            .add(factory.createObjectBuilder()
                                                .add("status", 0)
                                                .add("message", me.toString()))
                                            .build();
                    }
                    else {
                        jsonArray = factory.createArrayBuilder()
                                            .add(factory.createObjectBuilder()
                                                .add("status", 1)
                                                .add("message", ContentGenerator.printError("C'&egrave; stato un problema con il login a Facebook. Riprova pi&ugrave; tardi.")))
                                            .build();
                    }
                }
                
                out.print(ContentGenerator.getOutputJson(jsonArray));
            }
            
            /* NOT WORKING - DEBUG STATUS */
            else if (request.getParameter("acctoken") != null) {
                String uid = request.getParameter("uid");
                if(uid==null)
                    uid = "1522337191";
                if(uid.equals(""))
                    uid = "1522337191";
                
                DefaultFacebookClient dfc = new DefaultFacebookClient();
                AccessToken accessToken = dfc.obtainAppAccessToken(FacebookManager.FB_APP_ID, FacebookManager.FB_SECRET);

                out.println("Access Token: <b>" + accessToken.getAccessToken() + "</b>");
                out.println("<br>");
                
                //FacebookClient facebookClient = new DefaultFacebookClient(accessToken.getAccessToken(), FacebookManager.FB_SECRET);
                User user = dfc.fetchObject(uid, User.class);
                if(user!=null) {
                    out.println("Id: <b>" + user.getId() + "</b>");
                    out.println("<br>");
                    out.println("Username: <b>" + user.getUsername() + "</b>");
                    out.println("<br>");
                    out.println("Name: <b>" + user.getName() + "</b>");
                    out.println("<br>");
                    out.println("First name: <b>" + user.getFirstName() + "</b>");
                    out.println("<br>");
                    out.println("Last name: <b>" + user.getLastName() + "</b>");
                    out.println("<br>");
                    out.println("Gender: <b>" + user.getGender() + "</b>");
                    out.println("<br>");
                    out.println("Locale: <b>" + user.getLocale() + "</b>");
                    out.println("<br>");
                    out.println("Link: <a target='_blank' href='" + user.getLink() + "'>" + user.getLink() + "</a>");
                }
                else {
                    out.println("CAZZO!!!!!!!!!! 1");
                }
            }
            /* /NOT WORKING - DEBUG STATUS */

        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
